package cn.afactory.tygz.ui.fragments;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.common.CommType;
import cn.afactory.tygz.controller.CommunityController;
import cn.afactory.tygz.model.ApartmentInfo;
import cn.afactory.tygz.model.SnsCommentInfo;
import cn.afactory.tygz.model.SnsCommentInfoList;
import cn.afactory.tygz.model.SnsSubjectDetail;
import cn.afactory.tygz.ui.activities.ApartmentDetailActivity;
import cn.afactory.tygz.ui.base.BaseFragment;
import cn.afactory.tygz.R;
import cn.afactory.tygz.ui.base.adapter.CommentListAdapter;
import cn.afactory.tygz.ui.base.adapter.NearByForumsAdapter;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshListView;
import cn.afactory.tygz.ui.base.utils.DialogUtil;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;
import cn.afactory.tygz.ui.base.utils.sns.TimeUtil;
import cn.afactory.tygz.ui.base.views.community.ApartmentDetailHeaderView;
import cn.afactory.tygz.ui.sns.SendCommentActivity;

/**
 * Created by Kenneth on 15/9/17.
 */
public class ApartmentDetailFragment extends BaseFragment {

    private static final String TAG = ApartmentListFragment.class.getSimpleName();
    public static final int REQUEST_CODE_COMMENT = 0x1001;
    public static final String EXTRA_DES = "extraDes";

    private ApartmentInfo apartmentInfo;
    private CommentListAdapter mAdapter;
    protected CommunityController mController;
    private List<SnsCommentInfo> mList = new ArrayList<SnsCommentInfo>();

    private TextView mTvSend;
    private ApartmentDetailHeaderView apartmentDetailHeaderView;

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case CommunityController.MSG_GET_COMMUNITY_COMMENT_OK:
                if (msg.obj instanceof SnsCommentInfoList) {
                    hideErrorPage(-1);
                    SnsCommentInfoList t = (SnsCommentInfoList) msg.obj;
                    if (t.userInfoList != null && t.userInfoList.size() >= 0) {
                        if(mAdapter.getCount() == 0 && t.userInfoList.size() == 0){
//                            showNullPage(true);
                            return ;
                        }
                        try {
                            mList.addAll(t.userInfoList);
                            mAdapter.addDataAll(mList);
                            mPageIndex = (mList.size()/mPageSize) + 1;

                            if (plistview.isRefreshing()) {
                                plistview.onRefreshComplete();
                            }
                            if (t.userInfoList.size() < mPageSize) {
                                plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            } else {
                                plistview.setMode(PullToRefreshBase.Mode.BOTH);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
//                        if (mAdapter.getCount() == 0) {
//                            showNullPage(true);
//                        }
                    }
                }
                break;
            case CommunityController.MSG_GET_COMMUNITY_COMMENT_KO:
                if (mAdapter.getCount() == 0) {
//                    hideErrorPage(-1);
//                    showErrorPage(msg.arg1, new View.OnClickListener() {
//
//                        @Override
//                        public void onClick(View v) {
//                            startLoadData(true);
//                        }
//                    });
                } else {
                    LocalUtils.showToast(mContext, (String)msg.obj);
                }
                LocalUtils.showToast(mContext, (String)msg.obj);
                break;
            default:
                break;
        }

        // 结束下拉刷新
        if (plistview.isRefreshing()) {
            plistview.onRefreshComplete();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        apartmentInfo = (ApartmentInfo)getArguments().getSerializable(ApartmentDetailActivity.EXT_DATA_TAG);
        mController = new CommunityController(mContext, mUIHandler, "ApartmentDetail");
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fg_community_detail, null);
        initView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    private void initView(View view) {

        if (!TextUtils.isEmpty(apartmentInfo.name)) {
            setTitleText(apartmentInfo.name);
        } else {
            setTitleText("人才公寓详情");
        }

        plistview = (PullToRefreshListView) view.findViewById(R.id.plv_community);

        mTvSend = (TextView) view.findViewById(R.id.comment_send);
        mTvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TimeUtil.isFastDoubleClick()) {
                    return;
                }
                Intent intent = new Intent(mContext, SendCommentActivity.class);
                intent.putExtra(EXTRA_DES, "评论");
                intent.putExtra(SPUtils.EXTRA_TYPE, CommType.APARTMENT);
                intent.putExtra(SPUtils.EXTRA_POST_ID, apartmentInfo.id);
                startActivityForResult(intent, REQUEST_CODE_COMMENT);
            }
        });

        apartmentDetailHeaderView = new ApartmentDetailHeaderView(mContext, null, apartmentInfo);
        plistview.getRefreshableView().addHeaderView(apartmentDetailHeaderView, null, false);
        apartmentDetailHeaderView.setOnInfoItemClickListener(new ApartmentDetailHeaderView.OnInfoItemClickListener() {
            @Override
            public void onLocationInfoClick(ApartmentInfo apartmentInfo) {
                NaviUtils.launchNavigatorBd(apartmentInfo.lat, apartmentInfo.lng, getActivity(), showLoadingView("导航准备中..."));
            }

            @Override
            public void onPhoneNumInfoClick(String phoneNum) {
                LocalUtils.call(getActivity(), phoneNum);
            }
        });

        mAdapter = new CommentListAdapter(mContext, null);
        mAdapter.setOnItemClickLsn(new NearByForumsAdapter.OnItemClickListener() {
            @Override
            public void onPraise(TextView v, SnsSubjectDetail item) {

            }

            @Override
            public void onClickImage(int position, List<String> mPath) {

            }

            @Override
            public void onClickTopic(String topic, long topicId) {

            }

            @Override
            public void onClickShare(SnsSubjectDetail item) {

            }

            @Override
            public void onClickIcon(SnsSubjectDetail item) {

            }

            @Override
            public void onClickCommentIcon(SnsCommentInfo commentInfo) {
                NaviUtils.gotoUserProfileActivity(getActivity(), commentInfo.userId, commentInfo.userName);
            }

            @Override
            public void onClickSubjectList(String str) {

            }
        });
        mAdapter.setListType(1);
        plistview.setAdapter(mAdapter);
        plistview.setMode(PullToRefreshBase.Mode.BOTH);
        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadData(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadData(false);
            }
        });
    }

    private void initData(){
        startLoadData(true);
    }

    /**
     * 加载listview数据
     */
    private int mPageIndex = 1;
    private int mPageSize = 10;
    private long mLastReqTime = System.currentTimeMillis();
    public void startLoadData(boolean cleanData) {
        if (cleanData) {
            mPageIndex = 1;
            mLastReqTime = 0;
            mList.clear();
        }
        //请求评论数据
        mController.loadCommunityCommentList(apartmentInfo.id, mPageIndex, mPageSize, CommType.APARTMENT);
    }

}
